<?php

namespace app\admin\controller\shopro\user;

use app\common\library\Auth;
use fast\Random;
use think\Db;
use app\admin\controller\shopro\Common;
use addons\shopro\service\Wallet as WalletService;
use app\admin\model\shopro\user\User as UserModel;
use app\admin\model\shopro\user\Coupon as UserCouponModel;

class User extends Common
{
    protected $model = null;

    protected $noNeedRight = ['select'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new UserModel;
    }

    /**
     * 用户列表
     */
    public function index()
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }
        $data = db('user')->field('id,parent_id')->select();
//        foreach ($data as $k=>$v){
////            $arr = json_decode($v['user_json'],true);
////            dump($arr);exit();
//            db('user')->where(['id'=>$v['id']])->update(['parent_user_id'=> $v['parent_id']]);
//        }
//        exit();
        $data = $this->model->sheepFilter()->paginate($this->request->param('list_rows', 10));

        $this->success('获取成功', null, $data);
    }

    /**
     * 用户详情
     *
     * @param  $id
     */
    public function detail($id)
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        $user = $this->model->with(['third_oauth', 'parent_user'])->where('id', $id)->find();
        if (!$user) {
            $this->error(__('No Results were found'));
        }
        $user->is_experience_store = (string)$user->is_experience_store;
        $this->success('获取成功', null, $user);
    }

    /**
     * 用户详情
     *
     * @param  $id
     */
    public function add()
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }
        $params = $this->request->only([
            'nickname',
            'username',
            'password',
            'mobile',
            'email',
            'parent_user_id',
            'money',
            'gold',
            'golden',
            'silver',
            'score',
            'status'
        ]);
        if (empty($params['password'])) {
            $this->error('请填写密码');
        }
        $auth                     = new Auth();
        $extend['username']       = $params['username'];
        $extend['parent_user_id'] = $params['parent_user_id'];
        $extend['gold']           = $params['gold'];
        $extend['golden']         = $params['golden'];
        $extend['silver']         = $params['silver'];
        $extend['score']          = $params['score'];
        $extend['invite_code'] = Random::alnum(8);
        $ret =  $auth->register($params['nickname'], $params['password'], $params['email'], $params['mobile'], $extend);
        if($ret){
            $this->success('获取成功', '/shopro/user/user');
        }else{
            $this->error($auth->getError());
        }
    }

    /**
     * 获取密码加密后的字符串
     * @param  string  $password  密码
     * @param  string  $salt  密码盐
     * @return string
     */
    public function getEncryptPassword($password, $salt = '')
    {
        return md5(md5($password).$salt);
    }

    /**
     * 更新用户
     *
     * @param  $id
     * @return \think\Response
     */
    public function edit($id = null)
    {
        $params = $this->request->only([
            'username',
            'nickname',
            'mobile',
            'password',
            'avatar',
            'gender',
            'email',
            'status',
            'is_experience_store'
        ]);

        if (empty($params['password'])) {
            unset($params['password']);
        }
        if (empty($params['username'])) {
            unset($params['username']);
        }

        $params['id'] = $id;
        $this->svalidate($params, '.edit');
        unset($params['id']);

        $user = $this->model->where('id', $id)->find();
        $user->save($params);

        $this->success('更新成功', null, $user);
    }

    /**
     * 删除用户(支持批量)
     *
     * @param  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        if (empty($id)) {
            $this->error(__('Parameter %s can not be empty', 'id'));
        }

        $id     = explode(',', $id);
        $list   = $this->model->where('id', 'in', $id)->select();
        $result = Db::transaction(function () use ($list) {
            $count = 0;
            foreach ($list as $item) {
                $count += $item->delete();
            }

            return $count;
        });

        if ($result) {
            $this->success('删除成功', null, $result);
        } else {
            $this->error(__('No rows were deleted'));
        }
    }

    public function recharge()
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        $params = $this->request->only(['id', 'type', 'amount', 'memo']);
        if (!in_array($params['type'], ['money', 'score', 'golden', 'gold', 'silver'])) {
            error_stop('参数错误');
        }

        $result = Db::transaction(function () use ($params) {
            return WalletService::change($params['id'], $params['type'], $params['amount'], 'admin_recharge', [],
                $params['memo']);
        });
        if ($result) {
            $this->success('充值成功');
        }
        $this->error('充值失败');
    }


    /**
     * 用户优惠券列表
     */
    public function coupon($id)
    {
        $userCoupons = UserCouponModel::sheepFilter()->with('coupon')->where('user_id', $id)
            ->order('id', 'desc')->paginate($this->request->param('list_rows', 10));

        $this->success('获取成功', null, $userCoupons);
    }


    public function select()
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        $data = $this->model->sheepFilter()->paginate($this->request->param('list_rows', 10));

        $this->success('获取成功', null, $data);
    }
}
